# -*- coding: utf-8 -*-

from core.serializers import CustomModelSerializer
from core.relations import BaseNameWritableRelatedField, UserNameWritableRelatedField
from rest_framework import serializers
from apps.tms.models import TestCase, Bug
from apps.tms.bug.serializers import BugTreeSelectSerializer
from apps.tms.testcase.serializers import TestCaseTreeSelectSerializer
from .models import Module


class ListModuleSerializer(CustomModelSerializer):
    """
    产品模块-列表序列化器
    """

    product_name = serializers.CharField(read_only=True, source="product.name")
    reqs_count = serializers.SerializerMethodField()
    cases_count = serializers.SerializerMethodField()
    bugs_count = serializers.SerializerMethodField()

    def get_reqs_count(self, instance):
        return len(instance.requirement_set.all())

    def get_cases_count(self, instance):
        return len(instance.testcase_set.all())

    def get_bugs_count(self, instance):
        return len(instance.bug_set.all())

    class Meta:
        model = Module
        fields = "__all__"
        read_only_fields = ["id"]


class ModuleSerializer(CustomModelSerializer):
    """
    产品模块-查询、新增、修改序列化器
    """

    product = BaseNameWritableRelatedField()
    parent = BaseNameWritableRelatedField(
        required=False, allow_empty=True, allow_null=True
    )
    owner = UserNameWritableRelatedField(
        required=False, allow_empty=True, allow_null=True
    )

    class Meta:
        model = Module
        fields = "__all__"
        read_only_fields = ["id"]


class ModuleTreeSelectSerializer(CustomModelSerializer):
    """
    产品模块-树型菜单序列化器
    """

    type = serializers.SerializerMethodField(read_only=True)
    children = serializers.SerializerMethodField(read_only=True)

    def get_type(self, instance):
        return instance._meta.object_name

    def get_children(self, instance):
        children = []
        if self.request.query_params.get("showcase") == "true":
            queryset = TestCase.objects.filter(module=instance.id, status="0")
            children = TestCaseTreeSelectSerializer(
                queryset, many=True, request=self.request
            ).data
        if self.request.query_params.get("showbug") == "true":
            queryset = Bug.objects.filter(module=instance.id)
            children = BugTreeSelectSerializer(
                queryset, many=True, request=self.request
            ).data
        return children

    class Meta:
        model = Module
        fields = ("id", "name", "type", "number", "parent", "children")
        read_only_fields = ["id"]
